# encoding:utf-8
'''
@author: adog
web: http://www.adog.net.cn
Created on 2020-11-24
'''

import time
import datetime
import os
import platform
import socket
import pandas as pd
# 获取本机电脑�?
pcName = socket.getfqdn(socket.gethostname())


def timeString2timeLong(timeStr, format='day'):
    timeStruc = None
    if format == 'sec':
        timeStruc = time.strptime(timeStr, "%Y-%m-%d %H:%M:%S")
    elif format == 'min':
        timeStruc = time.strptime(timeStr, "%Y-%m-%d %H:%M")
    elif format == 'day':
        timeStruc = time.strptime(timeStr, "%Y-%m-%d")
    timeLong = int(time.mktime(timeStruc))
    return timeLong


def timeLong2Str(timeLong, format='sec'):  # timeLong unit: sec
    timeStr = ''
    if timeLong is not None:
        # timeLong/=1000
        if format == 'day':
            timeStr = time.strftime('%Y-%m-%d', time.localtime(timeLong))
        elif format == 'sec':
            timeStr = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeLong))
    return timeStr
    

def nowTime():
    now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    return now


def nowTimeShort():
    now = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    return now


def nowOnlyTime():
    now = time.strftime('%H:%M:%S', time.localtime(time.time()))
    return now


def nowOnlyTimeMins():
    now = time.strftime('%H:%M', time.localtime(time.time()))
    return now


def nowDateMins():
    now = time.strftime('%Y-%m-%d_%H:%M', time.localtime(time.time()))
    return now


def nowDate():
    nowDate = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    return nowDate


def getTimeBefAft(timeStr, x_seconds):
    x = time.mktime(time.strptime(timeStr, "%Y-%m-%d %H:%M:%S"))
    y = x + x_seconds
    z = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(y)) 
    return z


def getTimeDiff(timeStr1, timeStr2):
    x1 = time.mktime(time.strptime(timeStr1, "%Y-%m-%d %H:%M:%S"))
    x2 = time.mktime(time.strptime(timeStr1, "%Y-%m-%d %H:%M:%S"))
    diff = x2 - x1
    return  diff.seconds


def getDayDiff(dayStr1, dayStr2):
    x1 = datetime.datetime.strptime(dayStr1, "%Y-%m-%d")
    x2 = datetime.datetime.strptime(dayStr2, "%Y-%m-%d")
    diff = x2 - x1
    return  diff.days
 
    
def adogRootPath():
    sep = ''
    localPath = os.getcwd()
    if platform.uname()[0] == 'Linux':
        sep = '/'
        localPathList = localPath.split(sep)[:6]
    elif platform.uname()[0] == 'Windows':
        sep = '\\'
        localPathList = localPath.split(sep)[:4]
    out = sep.join(localPathList)
    return out


def filePath(filePath):
    path = 'wrong in file path'
    if platform.uname()[0] == 'Linux':
        path = adogRootPath() + path
    elif platform.uname()[0] == 'Windows':
        path = str(adogRootPath() + filePath).replace('/', '\\')
    return path


def code_wxy2jq(code, broker):
    pass


def code_jq2wxy(code, broker=None):
    
    if broker is None:
        cod = code.upper()[:2]
        # XZCE
        if cod in ['AP', 'CF', 'CJ', 'CY', 'FG', 'JR', 'LR', 'MA', 'OI', 'PF', 'PK', 'PM', 'RI', 'RM', 'RS', 'SA', 'SF', 'SM', 'SR', 'TA', 'UR', 'WH', 'ZC']:
            if len(code) <= 7:  # fut
                code = code.replace('21', '1')
            else:  # opt
                pass
        # XINE
        elif cod in ['BC', 'LU', 'NR', 'SC']:
            code = code.lower()
            
    else:
        code = code.upper()
        if broker == 'XSGE':
            pass
        elif broker == 'XZCE':
            if len(code) <= 7:  # fut
                code = code.replace('21', '1')
            else:  # opt
                pass
        elif broker == 'XDCE':
            if len(code) <= 7:  # fut
                pass
            else:  # opt
                pass
        elif broker == 'XINE':
            code = code.lower()
    
    return code


def getHtml(df, align='center', width='100%', classesName='tbl'):
    # d=df.copy()
    pd.set_option('display.max_colwidth', -1)
    # df.style.set_properties(**{'text-align': '%s'%(align)})
    
    html = df.to_html(classes=str(classesName))
    html = html.replace('<table border="1" class="dataframe %s"' % (classesName), '<table border="1" class="dataframe %s" width="%s"' % (classesName, width))
    html = html.replace('<tbody>', '<tbody style="text-align: %s;">' % (align))
    
    return html


# hasIndexCheckBox -whether has input checkbox for the columns
# hasFontID  whether has <font id ...> for each fields
def getHtmlTable(df,
                 exlusiveField=[],
                 classesName='tbl',
                 tbl_id='tbl',
                 border=1,
                 width='100%',  # 1800px or 100%
                 tbody_align='center',
                 hasIndexCheckBox=False,
                 indexCheckBoxName='',
                 key=[],
                 hasFontID=False,
                 fontKey=[],
                 global_suffix='',
                 global_prex='',
                 inputHiddenKeyField='',
                 textAreaFiled=[]
                 ):
    tbl = ''
    tbl = tbl + '<table id="%s" \
            bordercolor="#66666" border="%s" align="center" class="df %s" width="%s">' % (tbl_id,
                                                                                        border,
                                                                                         classesName,
                                                                                         width)
    
    tbl = tbl + '<thead style="background-color:#444444;" align="center">'
    tbl = tbl + '<td>index</td>'
    for c in df.columns:
        if c in exlusiveField:
            pass
        else:
            tbl = tbl + '<td>' + c + '</td>'
    tbl = tbl + '</thead>'       
    tbl = tbl + '<tbody style="text-align: %s;">' % (tbody_align)            
    for i in range(len(df)):
        if i % 2 == 0:
            tbl = tbl + '<tr style="background-color:#555555;">'
        else:
            tbl = tbl + '<tr>'
        
        if hasIndexCheckBox:
            if isinstance(df.index[i], int):
                tbl = tbl + '<td>' + '%s' % (df.index[i]) + '<input name="%s" type="checkbox" value="%s"/>' % (indexCheckBoxName, '_'.join(df.ix[i, key])) + '</td>'
            else:
                # judge whether is a multiIndex:
                if hasattr(df.index, 'levels'):
                    tbl = tbl + '<td>-</td>'   
                else:
                    tbl = tbl + '<td>' + '%s' % (df.index[i]) + '</td>'   
        else:
            # judge whether is a multiIndex:
            if hasattr(df.index, 'levels'):
                tbl = tbl + '<td>-</td>'   
            else:
                tbl = tbl + '<td>' + '%s' % (df.index[i]) + '</td>'   
            # tbl=tbl+'<td>'+'%s'%(df.index[i])+'</td>'   
           
        for c in df.columns:
            # if i==5 and c=='price':
            #    print(i,c)
            v = '%s' % df.ix[i, c]
            if hasFontID:
                fontKeyStr = '_'.join(df.ix[i, fontKey])
                v = '<font id="%s%s_%s%s">%s</font>' % (global_prex, fontKeyStr, c, global_suffix, df.ix[i, c])
            
            if inputHiddenKeyField != '':
                if c == inputHiddenKeyField:
                    v = "<input name='%s' type='hidden' value=''></input>" % (df.loc[i, inputHiddenKeyField])
            
            if len(textAreaFiled) > 0:
                if c in textAreaFiled:
                    v = '<textarea name="txtarea_%s" rows="3" cols="10" class="txt_area">%s</textarea>' % ('_'.join(df.ix[i, key]), df.loc[i, c]) 
            
            if c in exlusiveField:
                pass
            else: 
                tbl = tbl + '<td>' + v + '</td>'
                
        tbl = tbl + '</tr>'
    tbl = tbl + '</tbody></table>'
    return tbl   


def getSleepTime(planDailyTime=None, planWeeklyTime=None):
    sleepTime = None
    curTime = datetime.datetime.now()
    fullDaySeconds = 24 * 60 * 60 
    if planDailyTime is not None:
        hms = planDailyTime.split(":")
        h = int(hms[0])
        m = int(hms[1])
        s = int(hms[2])
        if nowOnlyTime() < planDailyTime:
            tommorrow = curTime  
        else:
            tommorrow = curTime + datetime.timedelta(days=1)   
        desTime = tommorrow.replace(year=tommorrow.year, month=tommorrow.month, day=tommorrow.day, hour=h, minute=m, second=s, microsecond=0)
        if desTime > curTime: 
            sleepTime = (desTime - curTime).total_seconds()
        else:
            sleepTime = fullDaySeconds - (curTime - desTime).total_seconds()
        print('\ncurTime:  %s\nstartTime:%s \nwaiting:%.0fs' % (curTime, desTime, sleepTime))
    
    return sleepTime


if __name__ == '__main__':
    code_jq2wxy('AG2105', 'XSGE')

